<script setup lang="ts">
	import { reactive, ref } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { route } from '@/uni_modules/uview-plus'
	import { useLocation } from '@/hooks/web/useLocation'
	import { storeList, storeCreate, getRegion } from '@/package_saleman/api/Home'
	import { useUserStore } from '@/stores/user'
	import { useNotify } from '@/hooks/web/useNotify/index.js'
	onShow(() => {
		paging.value?.refresh()
	})
	// 消息弹窗
	const NotifyRef = ref<any>(null)
	const { showNotify } = useNotify(NotifyRef)

	const { userInfo } = useUserStore()
	const { getLocation } = useLocation()
	const data = ref(0)
	const formData = ref({
		store_name: '',
		store_short_name: '',
		contacts: '',
		phone: '',
		address: '',
		store_region_id: '',
		lon: '',
		lat: '',
		store_img: ''
	})
	const rules = reactive({
		'store_name': {
			type: 'string',
			required: true,
			message: '请填写门店名称',
			trigger: ['blur', 'change'],
		},
		'contacts': {
			type: 'string',
			required: true,
			message: '请填写门店联系人',
			trigger: ['blur', 'change'],
		},
		'phone': {
			type: 'string',
			required: true,
			message: '请填写门店联系电话',
			trigger: ['blur', 'change'],
		},
		'address': {
			type: 'string',
			required: true,
			message: '请填写门店地址',
			trigger: ['blur', 'change'],
		}
	})

	// 使用 ref 创建响应式引用  
	const formRef = ref(null);

	const useUploadImg = () => {
		const fileList1 = ref<any[]>([])

		// 添加图片
		type UploadImageFile = {
			size : number,
			type : 'image',
			url : string,
			thumb : string
		}
		type UploadImageParams = {
			file : UploadImageFile | UploadImageFile[],
			index : number,
			name : string
		}
		type AddImage = (event : UploadImageParams) => any
		// 新增图片
		const addImage = async (event) => {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = fileList1.value.length;
			lists.map((item) => {
				fileList1.value.push({
					...item,
					status: 'uploading',
					message: '上传中',
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadImage(lists[i].url);
				let item = fileList1.value[fileListLen];
				fileList1.value.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: result,
				});
				fileListLen++;
			}
		};

		const uploadImage = (url) => {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: `${process.env.VUE_APP_BASE_URL}/salesman/upload`,
					filePath: url,
					name: 'file',
					header: {
						'content-type': 'application/json;charset=utf-8',
						'token': uni.getStorageSync('trioToken'),
					},
					success: (res) => {
						const data = JSON.parse(res.data)
						if (data.code !== 200) {
							uni.showToast({
								title: `${data.msg},请重新上传!`,
								icon: 'none'
							})
							return
						}
						setTimeout(() => {
							resolve(data.data.url);
						}, 1000);
					},
				});
			});
		};
		// 删除图片
		const delImage = (event : UploadImageParams) => {
			fileList1.value.splice(event.index, 1)
		}

		return {
			fileList1,
			addImage,
			delImage,
			uploadImage
		}
	}
	const { fileList1, addImage, delImage } = useUploadImg()

	// 选择地址
	const setAddress = () => {
		uni.chooseLocation({
			success: (res) => {
				if (res) {
					formData.value.address = `${res.address}${res.name}`
					formData.value.lon = res.longitude
					formData.value.lat = res.latitude
				}
			},
			fail: (err) => {
				console.log(err);
			}
		})
	}

	const submitLoading = ref(false)
	const submit = async () => {
		if (fileList1.value.length > 0) {
			formData.value.store_img = fileList1.value.map((item) => item.url).join(',')
		}
		formRef.value.validate().then(async () => {
			try {
				submitLoading.value = true
				const res = await storeCreate({ ...formData.value, only_phone: formData.value.phone })
				showNotify({
					type: 'success',
					message: res.msg,
					top: 0
				})
				addShow.value = false
				paging.value?.refresh()
				formRef.value.resetFields()
				fileList1.value = []
			} catch (error) {
				showNotify({
					type: 'error',
					message: error.msg,
					top: 0
				})
			} finally {
				submitLoading.value = false
			}
		})

	}
	// onLoad(() => {
	// 	tabsClick({ id: 1 })
	// 	getLocation()
	// 		.then((res) => {
	// 			const { longitude, latitude } = res
	// 			query.value.lat = latitude
	// 			query.value.lng = longitude
	// 			paging.value?.reload()
	// 		})
	// 		.catch((err) => {
	// 			showNotify({
	// 				type: 'error',
	// 				message: '请授权'
	// 			})
	// 		})
	// })

	const useTabs = () => {
		const tabsColumns = reactive([
			{
				name: '所有客户',
				id: 0
			},
			{
				name: '片区客户',
				id: 3
			}
			// {
			// 	name: '今日退单',
			// 	id: 2
			// }
		])
		return {
			tabsColumns
		}
	}
	const { tabsColumns } = useTabs()

	const paging = ref<ZPagingInstance>()
	const useCURD = () => {
		const dataList = ref([])
		const query = ref({
			today: '',
			// name: '',
			lng: '', // 经度
			lat: '', // 纬度
		})

		const getList : ZPagingEvent.Query = async (page : number, limit : number) => {
			try {
				const locationData = await getLocation();
				query.value.lat = locationData.latitude || ''
				query.value.lng = locationData.longitude || ''
				const params = { page, limit, ...query.value }
				try {
					const res = await storeList(params)
					data.value = res.data.total
					paging.value?.complete([...res.data.data])
				} catch (err) {
					paging.value?.complete(false)
				}
			} catch (err) {
				showNotify({
					type: 'error',
					message: '获取位置信息失败，请检查定位权限'
				})
			}
			// const params = { page, limit, ...query.value }
			// try {
			// 	const res = await storeList(params)
			// 	data.value = res.data.total
			// 	paging.value?.complete([...res.data.data])
			// } catch (err) {
			// 	paging.value?.complete(false)
			// }
		}

		const searchAction = () => {
			paging.value?.reload()
		}

		return {
			dataList,
			getList,
			searchAction,
			query
		}
	}
	const { dataList, getList, searchAction, query } = useCURD()
	// 导航
	const openLocation = (item) => {
		uni.openLocation({
			latitude: Number(item.lat),
			longitude: Number(item.lon),
			name: item.address
		})
	}

	// tabs切换
	const tabsClick = (index) => {
		query.value.today = index.id
		paging.value?.reload()
	}

	// 距离格式化
	const formatDistance = (distance : number) => {
		if (distance < 1000) {
			return `${distance.toFixed(2)} m`;
		} else {
			return `${(distance / 1000).toFixed(2)} km`;
		}
	};

	const toStoreDetail = (id : number) => {
		route({
			url: 'package_saleman/pages/Store/storeList',
			params: {
				id
			}
		})
	}

	const toStoreCreate = () => {
		route({
			url: '/package_saleman/pages/Store/createStore'
		})
	}
	const addShow = ref(false)
	const isFullTab = ref(false)
	// const tabList = ref([])
	// const getTabList = async () => {
	// 	const res = await getRegionList()
	// 	tabList.value = res.data
	// }
	// const tabList = ref([
	// 	{

	// 		title: '全部', children: [
	// 			{ title: '1',   price: 88 }
	// 		]
	// 	},
	// 	{

	// 		title: '中原区', children: [
	// 			{ title: '2',   price: 99 }
	// 		]
	// 	},
	// 	{

	// 		title: '金水区', children: [
	// 			{ title: '3',   price: 88 }
	// 		]
	// 	},
	// 	{

	// 		title: '郑东新区', children: [
	// 			{ title: '4',   price: 99 }
	// 		]
	// 	},
	// ]);
</script>

<template>
	<z-paging ref="paging" v-model="dataList" @query="getList" bg-color="rgba(242, 243, 245, 1)">
		<template #top>
			<up-navbar :title="'业务门店(' + data + ')'" autoBack placeholder></up-navbar>
			<view class="user_info_wrap">
				<view class="search-area">
					<view class="search-wrap">
						<up-search v-model="query.store_name" @search="searchAction" @custom="searchAction"
							@clear="searchAction" showAction actionText="搜索" animation shape="square"
							bgColor="rgba(243, 242, 245, 1)" placeholder="请输入门店名称"></up-search>
					</view>
					<view class="filter-right" @click="addShow = true">
						<image src="/package_saleman/static/img/filter.png" mode="aspectFit"></image>
						新增门店
					</view>
				</view>

				<view class="user-info">
					<view class="avatar-wrap">
						<up-tabs :list="tabsColumns" :activeStyle="{ color: 'rgba(54, 116, 242, 1)' }"
							:itemStyle="{ height: '104rpx', fontSize: '28rpx' }" lineWidth="104rpx"
							lineColor=" rgba(54, 116, 242, 1)" :scrollable="false" @click="tabsClick">
							<!-- <template #right>
                <view style="padding-left: 4px;" @click="toStoreCreate">
                    <up-icon name="plus" size="21" bold></up-icon>
                </view>
              </template> -->
						</up-tabs>
					</view>
				</view>
			</view>
		</template>
		<view class="main">
			<view class="main-box" v-for="(item,index) in dataList" :key="index">
				<view class="main-header">
					<view class="header-name">{{item.store_name}}
					</view>
					<view class="header-right" @click="openLocation(item)">
						<view class="right-img">
							<image style="width: 34rpx;height: 34rpx;" src="/static/icon/icon1.png">
							</image>
						</view>
						<view class="right-name">导航去此处</view>
					</view>
				</view>
				<view @click="toStoreDetail(item.id)">
					<view class="mian-address">
						<view class="address-name">距离：{{formatDistance(Number(item.distance))}}</view>
						<!-- <view class="distance-name">{{formatDistance(Number(item.distance))}}</view> -->
					</view>
					<view class="line"></view>
					<view class="main-jl"><text style="color: rgba(2, 14, 36, 1);">门店地址：{{item.address}}</text>
					</view>
					<view class="main-jl">最近下单：<text style="color: rgba(2, 14, 36, 1);">{{item.newly_order_day}}</text>
					</view>
					<!--<view class="main-jl">最近签到：
						<text style="color: rgba(2, 14, 36, 1);">
							无
							 {{item.is_sign_text + '  '}}{{item.sign_time}}
						</text>
					</view> -->
				</view>
			</view>
		</view>

		<!-- <view class="cate" v-else>
			<up-cate-tab class="cate-tab" :tabList="tabList" tabKeyName="title">
				<template #pageItem="{pageItem}">
					<view class="w-full">
						<up-cell-group :border='false'>
							<up-cell :border='false'>
								<template v-slot:title>
									<view>
										{{ pageItem.title }}
									</view>
								</template>
								<template v-slot:label>
									<view class="h-100 pt-1">
										<text class="text-md text-red">￥{{ pageItem.price }}</text>
									</view>
								</template>
								<template v-slot:value>
									<up-number-box></up-number-box>
								</template>
							</up-cell>
						</up-cell-group>
					</view>
				</template>
			</up-cate-tab>
		</view> -->
		<up-notify ref="NotifyRef"></up-notify>
	</z-paging>
	<up-popup v-model:show="addShow" mode="bottom" :round="10" :customStyle="{height: '75vh',padding: '36rpx'}">
	    <view style="text-align: center; font-size: 32rpx; font-weight: bold; margin-bottom: 10rpx;">新增门店</view>
	    <view style="padding: 0 32rpx;">
	        <up-form labelPosition="left" labelWidth="75" :model="formData" :rules="rules" ref="formRef">
	            <up-form-item label="门店名称" prop="store_name" borderBottom required>
	                <up-input v-model="formData.store_name" border="none" placeholder="请填写门店名称"></up-input>
	            </up-form-item>
	            <up-form-item label="门店简称" prop="store_short_name" borderBottom>
	                <up-input v-model="formData.store_short_name" border="none" placeholder="请填写门店简称"></up-input>
	            </up-form-item>
	            <up-form-item label="联系人" prop="contacts" borderBottom required>
	                <up-input v-model="formData.contacts" border="none" placeholder="请填写门店联系人"></up-input>
	            </up-form-item>
	            <up-form-item label="联系电话" prop="phone" borderBottom required>
	                <up-input v-model="formData.phone" border="none" placeholder="请填写门店联系电话"></up-input>
	            </up-form-item>
	            <up-form-item label="地址" prop="address" borderBottom required @click="setAddress">
	                <up-input v-model="formData.address" border="none" placeholder="点击选择门店地址" readonly></up-input>
	            </up-form-item>
	            <up-form-item label="店面图片" prop="store_img" borderBottom>
	                <up-upload :fileList="fileList1" :previewFullImage="true" maxCount="3" @afterRead="addImage"
	                    @delete="delImage" multiple></up-upload>
	            </up-form-item>
	        </up-form>
	
	        <up-notify ref="NotifyRef"></up-notify>
	    </view>
	    <view class="fixed-button">
	        <up-button @click="submit" type="primary" :loading="submitLoading" :disabled="submitLoading">提交</up-button>
	    </view>
	</up-popup>
</template>

<style scoped lang="scss">
	.user_info_wrap {
		@include flex();
		flex-direction: column;
		justify-content: flex-end;
		gap: 20rpx;
		width: 100%;
		height: 249rpx;
		background-color: #FFFFFF;
		padding: 0 40rpx 0rpx;
		box-sizing: border-box;

		.search-area {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.search-wrap {
				display: flex;
				flex: 2;
				align-items: center;
				width: 100%;
				height: 64rpx;
				border-radius: 20rpx;
				padding: 10rpx;
				background: rgba(243, 242, 245, 1);
			}

			.filter-right {
				display: flex;
				align-items: center;
				justify-content: space-around;
				color: #fff;
				margin-left: 12rpx;
				padding: 0 24rpx;
				height: 72rpx;
				border-radius: 12rpx;
				flex: 1;
				background-color: rgba(15, 127, 255, 1);

				image {
					width: 30rpx;
					height: 30rpx;
				}
			}
		}
	}

	.main {
		width: 100%;
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);

		/* 兼容iOS 11.2及以上 */
		.main-box {
			width: 702rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			padding: 30rpx;
			box-sizing: border-box;
			margin: 20rpx auto;

			.main-header {
				display: flex;
				justify-content: space-between;
				padding: 0 12rpx;

				.header-name {
					font-size: 28rpx;
					font-weight: 700;
					color: rgba(2, 14, 36, 1);
				}

				.header-right {
					display: flex;
					justify-content: space-between;
					// background: rgba(15, 127, 255, 0.1);
					padding: 16rpx;

					.right-img {
						width: 34rpx;
						height: 34rpx;
						vertical-align: middle;
						margin-right: 10rpx;
					}

					.right-name {
						font-size: 28rpx;
						font-weight: 700;
						color: rgba(55, 131, 252, 1);
					}
				}
			}

			.mian-address {
				display: flex;
				justify-content: space-between;
				// margin-top: 20rpx;

				.address-name {
					width: 80%;
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(100, 101, 102, 1);
				}

				.distance-name {
					font-size: 24rpx;
					font-weight: 500;
					color: rgba(156, 154, 161, 1);
				}
			}

			.line {
				width: 572rpx;
				height: 4rpx;
				margin: 20rpx 0rpx;
				background: linear-gradient(90deg, rgba(55, 131, 252, 1) 0%, rgba(255, 255, 255, 0) 100%);
			}

			.main-jl {
				font-size: 28rpx;
				font-weight: 500;
				color: rgba(101, 103, 105, 1);
				margin-bottom: 20rpx;
			}

		}
	}
	.cate {
		.cate-tab {
		    height: calc(100vh - 150px);
		    /* #ifdef H5 */
		    height: calc(100vh - 150px - var(--window-top));
		    /* #endif */
		}
	}
	.fixed-button {
		position: fixed;
		bottom: 20rpx;
		left: 50%;
		transform: translateX(-50%);
		width: calc(100% - 40rpx);
		padding: 20rpx;
		box-sizing: border-box;
		text-align: center;
	}
</style>